using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Caching;

namespace IWS.Lib.SingleSignOn
{
	public class SettingCache
	{
		/// <summary>
		/// At application start, load all app settings into the cache and make them available. 
		/// </summary>
		public static void InitializeCache()
		{
			if (System.Web.HttpContext.Current.Cache["Settings"] != null)
			{
				System.Web.HttpContext.Current.Cache.Remove("Settings");
			}

			Dictionary<string, string> settings = IWS.Lib.SingleSignOn.Setting.ListAllByDictionary();

			System.Web.HttpContext.Current.Cache.Insert("Settings", settings, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));
		}

		/// <summary>
		/// Retrieve a setting in cache by its key
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string GetSetting(string key)
		{
			object oSettings = System.Web.HttpContext.Current.Cache.Get("Settings");
			if (oSettings == null)
			{
				SettingCache.InitializeCache();
				oSettings = System.Web.HttpContext.Current.Cache.Get("Settings");
			}

			Dictionary<string, string> settings = oSettings as Dictionary<string, string>;
			if (settings != null)
			{
				if (settings.ContainsKey(key))
					return settings[key];
				else
					throw new Exception("Setting not found [" + key + "].");
			}
			return null;
		}

		/// <summary>
		/// Save a cached setting
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public static void SaveSetting(string key, string value)
		{
			object oSettings = System.Web.HttpContext.Current.Cache.Get("Settings");
			if (oSettings == null)
			{
				SettingCache.InitializeCache();
				oSettings = System.Web.HttpContext.Current.Cache.Get("Settings");
			}


			Dictionary<string, string> settings = oSettings as Dictionary<string, string>;
			if (settings != null)
			{
				if (settings.ContainsKey(key))
				{
					settings[key] = value;
				}
				else
				{
					settings.Add(key, value);
				}
			}
		}
	}
}
